<template>
  <el-container class="main" v-loading="isTurning" element-loading-text='设备初始化中' element-loading-spinner="el-icon-loading">
    <el-container class="main-area">
      <el-main>
        <el-row class="main-pd">
          <div class="tips">
            请按照下方提示内容，根据指令时间吸气、摒弃、呼气
          </div>
          <Tips
            :isWork="status"
            width="1300px"
            height="550px"
            :bgColor="color"
            textColor="000"
            :content="content"
            :count="count"
            :initNum='initNum'
            :phase='curPhase'
            :imageSrc = 'image'
          ></Tips>
        </el-row>
        <el-row class="foot">
          <div class="btn" @click="()=>{begin('loosen')}">痰液松动</div>
          <div class="btn" @click="()=>{begin('move')}">痰液移动</div>
          <!-- <div class="btn" @click="pause">{{pauseMessage}}</div> -->
          <div class="btn" @click="stop">结束</div>
          </div>
        </el-row>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
// import Plt from '../components/echart'
import Tips from "../components/tips";
import * as echarts from "echarts";
import EventBus from "../utils/eventbus";

export default {
  name: "PaitanTrain",
  components: {
    Tips,
  },
  data() {
    return {
      content: "即将进入辅助排痰请做好准备",
      count: 3,
      status: false,
      color: "#fff",
      timer: null,
      isPause: false,
      chart1Data: new Array(25).fill(0),
      timer2: null,
      resultData: [],
      // 阀门换向标志位
      isTurning: false,
      isReady: false,
      userMsg:{},
      initNum:3,
      times:1,
      curPhase:1,
      image:''
    };
  },
  computed: {
    option1() {
      let _this = this;
      return {
        title: {
          text: "实时流量",
        },
        tooltip: {},
        xAxis: {
          data: Array(this.chart1Data.length).fill(""),
        },
        yAxis: {
          type: "value",
          min: 0,
          max: 20,
          axisLabel: {
            formatter: '{value} L/min',
            align: 'center'
          },
        },
        series: [
          {
            name: "流量",
            type: "line",
            data: _this.chart1Data,
          },
        ],
      };
    },
  },
  methods: {
    changeResultData(resultData) {
      console.log("train界面的result", resultData);
      localStorage.removeItem("result")
      localStorage.setItem("result", resultData);
    },
    init() {
      clearTimeout(this.timer);
      this.content = "3S后,即将进入辅助排痰请做好准备";
      this.count = 3;
      this.status = false;
      this.color = "#C1FFFC";
      this.timer = null;
      this.isPause = false;
      this.pauseMessage = "暂停";
      this.chart1Data = new Array(25).fill(0);
      this.isReady=false
    },
    countdown() {
      return new Promise((resolve, reject) => {
        this.timer = setTimeout(() => {
          if (!this.isPause) {
            this.count--;
            resolve();
          }
        }, 1000);
      });
    },
    async countSecond(num) {
      this.count = num;
      while (this.count >= 0) {
        await this.countdown();
      }
    },
    async oneAction(content, num, phase,img) {
      this.curPhase=phase
      this.image=img
      this.initNum = num
      this.content = content;
      await this.countSecond(num);
    },
    async oneLoop() {

      if(!this.isReady){
        this.status &&
          (await this.oneAction(
            "即将进入辅助排痰请做好准备",
            3,
            1,
            ''
          ));
        this.isReady = true
      }
      this.status &&
        (await this.oneAction("请尽力吸气4秒钟", 4, 2,"../assets/xiqi.png"));
      this.status && (await this.oneAction("请屏住呼吸3秒钟", 3,3, "../assets/baochi.png"));
      this.status && (await this.oneAction("请平稳呼气7秒钟", 7, 4,"../assets/huqi.png"));
      // -----
      if(this.status){
        this.oneLoop()
      }
    },
    changeFlowData(data) {
      // 接受webSocket传过来的实时流量数据
      this.chart1Data = data;
    },
    async begin(type) {
      if (!window.socket) {
        this.$message({
          message: "socket未连接，请连接设备",
          type: "error",
        });
        return;
      }
      this.init();
      console.log(type)
      window.socket.send(type);
      this.isTurning = true;
      this.status = true;
      await new Promise((resolve) => {
        setTimeout(() => {
          this.isTurning = false;
          resolve();
        }, 10000);
      });
      await this.oneLoop();
    },
    stop() {
      window.socket.send("cancel");

      this.status = false;
      this.color = "#C1FFFC";
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.confirm();
    },
    toNext() {
      this.$router.push({ path: "/paitan" });
    },
    confirm() {
      this.$confirm("是否前往查看训练结果？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "是",
        cancelButtonText: "否",
      })
        .then(() => {
          this.toNext();
        })
        .catch((action) => {
          this.init();
        });
    },
  },
  mounted() {
    EventBus.$on("flow", this.changeFlowData);
    EventBus.$on("result", this.changeResultData);
  },
};
</script>

<style scoped>
.tips {
  margin-top: 20px;
  margin-bottom: 30px;
  font-size: 36px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
  line-height: 50px;
  background: linear-gradient(170deg, #37BE98 0%, #0F7DDF 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.main-area{
  margin-top: 100px;
  background-color: #fff;
}
.main-pd {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.aside-pd {
  width: 490px;
  display: flex;
  /* height: 100%; */
  flex-direction: column;
  align-items: center;
  /* justify-content: flex-end; */
  background-color: #fff;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 500px;
  height: 100px;
  background: linear-gradient(170deg, #37BE98 0%, #0F7DDF 100%);
  border-radius: 4px;
  color: #fff;
  font-size: 40px;
  font-weight: 600;
  /* margin-bottom: 50px; */
  line-height: 60px;
  cursor: pointer;
}
.btn-img {
  width: 60px;
  height: 60px;
  margin-left: 20px;
}
.change-btn1 {
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 100px;
  text-align: center;
  color: #009fc7;
  background-color: #fff;
  line-height: 100px;
  font-weight: 600;
  font-size: 40px;
  border-radius: 30px;
  border: 3px solid #ccc;
  cursor: pointer;
}
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-aside {
  padding-top: 100px;
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
}
.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  line-height: 160px;
}

.foot {
  display: flex;
  margin-top: 30px;
  justify-content: space-between;
  align-items: center;
}
</style>
